package com.qx.cn.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.cn.model.OrgInfo;
import com.qx.cn.model.SendDate;
import com.qx.cn.model.SendTime;
import com.qx.cn.model.User;
import com.qx.cn.model.WorkReport;
import com.qx.cn.model.WorkReportItem;
import com.qx.cn.model.WorkSendGroup;
import com.qx.cn.service.OrgInfoService;
import com.qx.cn.service.SendDateService;
import com.qx.cn.service.SendEmailService;
import com.qx.cn.service.SendTimeService;
import com.qx.cn.service.WorkReportItemService;
import com.qx.cn.service.WorkReportService;
import com.qx.cn.service.WorkSendGroupService;
import com.qx.cn.tool.DateForm;

@Controller
@RequestMapping("/permission")
public class WorkReportAppController
{
    @Autowired
    HttpServletRequest request;
    
    @Autowired
    private OrgInfoService orgInfoService;
    
    @Autowired
    private SendDateService sendDateService;
    
    @Autowired
    private SendTimeService sendTimeService;
    
    @Autowired
    private WorkReportService workReportService;
    
    @Autowired
    private WorkSendGroupService workSendGroupService;
    
    @Autowired
    private WorkReportItemService workReportItemService;
    
    @Autowired
    private SendEmailService seService;
    
    public JSONObject addWorkReport(String item, Integer time)
        throws ParseException, UnsupportedEncodingException
    {
        // 更新日报汇总数据
        List<WorkSendGroup> sendGroups = seService.queryWorkSendGroup();
        if (!sendGroups.isEmpty())
        {
            Date now = new Date();
            if (seService.checkIsSendDate(DateForm.SimpleDate(now)) && seService.notSend(DateForm.SimpleDate(now))) // 判断当天是否需要发日报
            {
                SendDate sysSendDate = seService.queryBySendDate(DateForm.SimpleDate(now));
                List<SendTime> sendTimes = seService.querySendTimes();
                if (!sendTimes.isEmpty())
                {
                    for (WorkSendGroup wGroup2 : sendGroups)
                    {
                        if (wGroup2.getTimeTip() == 1 && StringUtils.isNotEmpty(wGroup2.getSenderIds()))
                        {
                            String[] wGroups = wGroup2.getSenderIds().split(",");
                            for (int i = 0; i < wGroups.length; i++)
                            {
                                seService.insertManageWorkReport(Integer.valueOf(wGroups[i]), wGroup2.getWorkerIds(), wGroup2.getGroupName(), sysSendDate.getType());
                            }
                        }
                    }
                }
            }
        }
        boolean flag = false;
        String errorMsg = "";
        Integer status = 2;
        User user = (User)request.getSession().getAttribute("user");
        List<SendTime> sendTimes = sendTimeService.queryAllTimeToShow();
        if (user != null)
        {
            if (sendTimes.size() > 0)
            {
                String sTimeStr = DateForm.SimpleDate(new Date()) + " " + ((SendTime)sendTimes.get(0)).getStartTime() + ":00";
                String eTimeStr = DateForm.SimpleDate(new Date()) + " " + ((SendTime)sendTimes.get(0)).getEndTime() + ":00";
                boolean tFlag = new Date().before(DateForm.StrToDateTime(sTimeStr));
                if (tFlag)
                {
                    flag = false;
                    errorMsg = "<span style='font-size:15px;'>还没有到日报允许上交时间,上交时间为【" + ((SendTime)sendTimes.get(0)).getStartTime() + "】!</span>";
                }
                else
                {
                    boolean etFlag = new Date().after(DateForm.StrToDateTime(eTimeStr));
                    if (etFlag)
                    {
                        flag = false;
                        errorMsg = "<span style='font-size:15px;'>已经过了截止发送时间,请自行发给相关负责人!</span>";
                    }
                    else
                    {
                        List<WorkSendGroup> workSendGroups = workSendGroupService.queryIsNotUserByUserId(user.getUserId());
                        if (workSendGroups.size() > 0)
                        {
                            SendDate sendDate = sendDateService.queryAllSendDateByDate(DateForm.SimpleDate(new Date()), "day");
                            if (sendDate != null)
                            {
                                boolean isFlag = workReportService.queryCheckIsWorkReports(DateForm.SimpleDate(new Date()), user.getUserId(), "day");
                                if (isFlag)
                                {
                                    String uuidCode = UUID.randomUUID().toString();
                                    WorkReport workReport = new WorkReport();
                                    workReport.setWorkReportName(DateForm.SimpleDate(new Date()) + "日报");
                                    workReport.setCreateTime(DateForm.SimpleDateTime(new Date()));
                                    workReport.setUserId(Integer.valueOf(user.getUserId().intValue()));
                                    workReport.setUserName(user.getUserName());
                                    OrgInfo orgInfo = orgInfoService.loadOrgByCode(user.getOrgCode());
                                    if (orgInfo != null)
                                    {
                                        workReport.setOrgName(orgInfo.getOrgName());
                                    }
                                    else
                                    {
                                        workReport.setOrgName("");
                                    }
                                    workReport.setPosition(user.getPositionName());
                                    workReport.setReportCode(uuidCode);
                                    flag = workReportService.saveWorkReport(workReport);
                                    WorkReportItem mpd = new WorkReportItem();
                                    mpd.setContent(URLDecoder.decode(URLDecoder.decode(item, "UTF-8"), "UTF-8"));
                                    mpd.setReportCode(uuidCode);
                                    mpd.setCreateTime(DateForm.SimpleDateTime(new Date()));
                                    mpd.setWorkTime(String.valueOf(time));
                                    flag = workReportItemService.saveWorkReportItem(mpd);
                                }
                                else
                                {
                                    WorkReport workReport = workReportService.loadWorkReportByUserAndDate(DateForm.SimpleDate(new Date()), user.getUserId());
                                    WorkReportItem mpd = new WorkReportItem();
                                    mpd.setContent(URLDecoder.decode(URLDecoder.decode(item, "UTF-8"), "UTF-8"));
                                    mpd.setReportCode(workReport.getReportCode());
                                    mpd.setCreateTime(DateForm.SimpleDateTime(new Date()));
                                    mpd.setWorkTime(String.valueOf(time));
                                    flag = workReportItemService.saveWorkReportItem(mpd);
                                }
                            }
                            else
                            {
                                flag = false;
                                errorMsg = "<span style='font-size:15px;'>今天不需要上交日报!</span>";
                            }
                        }
                        else
                        {
                            flag = false;
                            errorMsg = "<span style='font-size:15px;'>今天你不需要上交日报!</span>";
                        }
                    }
                }
            }
            else
            {
                errorMsg = "<span style='font-size:15px;'>还没有设置日报发送时间!</span>";
            }
        }
        else
        {
            flag = false;
            status = Integer.valueOf(3);
        }
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", 1);
        }
        else
        {
            object.put("result", status);
            object.put("errorMsg", errorMsg);
        }
        return object;
    }
    
    public JSONObject queryWorkItemList()
    {
        JSONObject object = new JSONObject();
        User user = (User)request.getSession().getAttribute("user");
        if (user != null)
        {
            WorkReport workReport = workReportService.loadWorkReportByUserAndDate(DateForm.SimpleDate(new Date()), user.getUserId());
            if (workReport != null)
            {
                List<WorkReportItem> workReportItems = workReportItemService.queryWorkReportItems(workReport.getReportCode());
                JSONArray jsonArray = new JSONArray();
                for (WorkReportItem wItem : workReportItems)
                {
                    JSONObject json = new JSONObject();
                    json.put("id", wItem.getId());
                    json.put("content", "[" + wItem.getWorkTime() + "小时]&nbsp;" + wItem.getContent());
                    json.put("time", wItem.getWorkTime());
                    json.put("info", wItem.getContent());
                    json.put("createTime", wItem.getCreateTime());
                    jsonArray.add(json);
                }
                object.put("datas", jsonArray);
            }
            object.put("result", 1);
        }
        else
        {
            object.put("result", 2);
        }
        return object;
    }
    
    public JSONObject deleteWorkItem(Integer id)
        throws ParseException
    {
        boolean flag = false;
        Integer status = 1;
        String errorMsg = "";
        User user = (User)request.getSession().getAttribute("user");
        if (user != null)
        {
            List<SendTime> sendTimes = sendTimeService.queryAllTimeToShow();
            if (sendTimes.size() > 0)
            {
                String eTimeStr = DateForm.SimpleDate(new Date()) + " " + ((SendTime)sendTimes.get(0)).getEndTime() + ":00";
                boolean nMFlag = new Date().after(DateForm.StrToDateTime(eTimeStr));
                if (nMFlag)
                {
                    flag = false;
                    status = 2;
                    errorMsg = "<span style='font-size:15px;color:red;'>该日报已经发送,不可删除!</span>";
                }
                else
                {
                    WorkReportItem workReportItem = workReportItemService.loadWorkItem(id);
                    flag = workReportItemService.deleteWorkItemById(id);
                    List<WorkReportItem> workReportItems = workReportItemService.queryWorkReportItems(workReportItem.getReportCode());
                    if (workReportItems.size() == 0)
                    {
                        flag = workReportService.deleteWorkReportCode(workReportItem.getReportCode());
                    }
                }
            }
            else
            {
                flag = false;
                status = 2;
                errorMsg = "<span style='font-size:15px;color:red;'>还没有设置日报发送时间!</span>";
            }
        }
        else
        {
            status = Integer.valueOf(3);
        }
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", 1);
        }
        else
        {
            object.put("result", status);
            object.put("errorMsg", errorMsg);
        }
        return object;
    }
    
    public JSONObject queryItemInfos()
    {
        boolean flag = false;
        JSONObject object = new JSONObject();
        User user = (User)request.getSession().getAttribute("user");
        if (user != null)
        {
            flag = true;
            WorkReport workReport = workReportService.loadWorkReportByUserAndDate(DateForm.SimpleDate(new Date()), user.getUserId());
            if (workReport != null)
            {
                object.put("workReportName", workReport.getWorkReportName());
            }
            else
            {
                object.put("workReportName", "日报详情");
            }
            List<WorkReportItem> workReportItems = workReportItemService.queryWorkReportItems(workReport.getReportCode());
            JSONArray jsonArray = new JSONArray();
            for (WorkReportItem wItem : workReportItems)
            {
                JSONObject json = new JSONObject();
                json.put("content", wItem.getContent() + "&nbsp;[" + wItem.getWorkTime() + "小时]");
                jsonArray.add(json);
            }
            object.put("datas", jsonArray);
        }
        if (flag)
        {
            object.put("result", 1);
        }
        else
        {
            object.put("result", 2);
        }
        return object;
    }
}